﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace TetrisV1._0
{
    class DBControl
    {
        static MySqlDataReader reader = null;
        public static MySqlConnection GetConnection()
        {
            String connetStr = "server=127.0.0.1;port=3306;user=root;password=root; database=tetris;";
            // server=127.0.0.1/localhost 代表本机，端口号port默认是3306可以不写
            MySqlConnection conn = new MySqlConnection(connetStr);
            try
            {
                conn.Open();//打开通道，建立连接，可能出现异常,使用try catch语句
                Console.WriteLine("已经建立连接");
                return conn;
                //在这里使用代码对数据库进行增删查改
            }
            catch (MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            return null;
        }

        public void CloseConnection(MySqlConnection conn)
        {
            if(null != conn)
            {
                conn.Close();
            }
        }

        public string GetScore(MySqlConnection conn)
        {
            string sql = @"SELECT * FROM score ORDER BY score DESC LIMIT 1;";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            reader = cmd.ExecuteReader();//执行ExecuteReader()返回一个MySqlDataReader对象
            string maxScore = "0" ;
            while (reader.Read())//初始索引是-1，执行读取下一行数据，返回值是bool
            {
                maxScore = reader.GetString("score");
                DateTime dataTime = reader.GetDateTime("createtime");
                //Console.WriteLine(reader.GetInt32("userid") + reader.GetString("username") + reader.GetString("password"));//"userid"是数据库对应的列名，推荐这种方式
            }
            reader.Close();
            return maxScore;
        }

        public bool InsertScore(MySqlConnection conn, int score)
        {
            string sql = "insert into score(score) values('"+score+"')";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            //执行插入语句。执行成功返回受影响的数据的行数，返回1可做true判断。执行失败不返回任何数据，报错，下面代码都不执行
            int result = cmd.ExecuteNonQuery();

            return (result == 1);
        }
        
    }
}
